var num = '';
var i = 0;
var picnum = 0;
var PicturePath1 = "";
var PicturePath2 = "";
var PicturePath3 = "";
$(document).ready(function(){	
	$("#addUser").val(username);
	console.log("页面中file的数量"+$("input[type=file]").length);
	queryProvince(document.getElementById("provinceId"));
	//下拉初始化
	InitParentCate();
	//父分类切换
	$("#parentCate1").change(function(){		
		var parentId=$(this).val();
		changeChildKv(parentId);
	});
	//子分类切换
	$("#parentCate2").change(function(){		
		var cateId=$(this).val();
		InitProduct(cateId);
		changeParentBrandIdKv(cateId);
		
	});
	//发布方式切换
	$("#saleStatus").change(function(){
		var status=$(this).val();
		console.log(status);
		if(status == ''){
			//$("#saleStatus").css("display","none");
			$("#person").css("display","none");
			$("#area").css("display","none");
		}else if(status == 4 || status == 3){
			$("#person").css("display","none");
			$("#area").css("display","block");	
		}
		if(status == 0 || status == 1 ){
			$("#area").css("display","none");
			$("#person").css("display","block");	
		}
		if(status == 5 || status == 6 ){
			$("#area").css("display","none");
			$("#person").css("display","none");	
		}
		//changeProductPic(parentBrandId);
		
	});
//表单验证
var validate = $("#fromProduct").validate({		   
		rules:{					
			productName:{
				  required:true,
			      remote: { 
	                   url: server_url+'/rest/product/checkProductName.do?timestamp='+Math.random()+ '&token=' + token,
	                   type: "post",
	                   dataType: "json", 
	                   data: {			                	     
	                	         productName: function() { return $("#productName").val();}
	                         } 
	               },
	               stringMaxLength:30
			},
			
			parentCate2:{
				required:true
               },
           
            parentBrand2:{
      	         required:true
                },
           productName:{
      			     required:true
               },
           catchId:{
            	   required:true
               },
           specId:{
               	   required:true
                },
           weightId:{
                  required:true
                },
           price:{
                 required:true
                /* remote:{
                	 
                 }*/
               },
           overPlusNum:{
                 required:true
			     /*remote:{
					                	 
					 }*/
                },
            saleStatus:{
                required:true
               },
           mobile:{
        	   required:true,
        	   isMobile: true,
        	   remote: { 
                   url: server_url+'rest/saleManager/checkIsExist.do?timestamp='+Math.random()+ '&token=' + token,
                   type: "get",
                   dataType: "json",
                   data: {			                	     
                	         mobile: function() { return $("#mobile"+num+"").val();},
                	         saleStatus:function(){return $("#saleStatus").val();}
                         } 
               }   
           }
		},
		messages:{				
			productName:{
			      required:"该值不能为空！",
                 },
           parentCate2:{
        	   required:"该值不能为空！"
             },
          
           parentBrand2:{
        	   required:"该值不能为空！"
             },
           productName:{
   			     required:"该值不能为空！"
                },
           catchId:{
        	   required:"该值不能为空！"
              },
           specId:{
           	   required:"该值不能为空！"
              },
           weightId:{
              required:"该值不能为空！"
             },
           price:{
              required:"该值不能为空！"
            },
          overPlusNum:{
               required:"该值不能为空！"
              },
          saleStatus:{
               required:"该值不能为空！"
             },
           mobile:{
        	   required:"该值不能为空！",
        	  remote:"该用户不存在！请重新输入！"
           }
		},
		submitHandler:function(){
			sub();
		},
		errorPlacement: function(error, element) {
			if ( element.is(":radio") )
				error.appendTo ( element.parent() );
			else if ( element.is(":checkbox") )
				error.appendTo ( element.parent() );
			else if ( element.is("input[name=captcha]") )
				error.appendTo ( element.parent() );
			else
				error.insertAfter(element);
		},
		validClass : 'rightValidate',
	    success: function(label) {
		   label.html("&nbsp;").text(" ") ;
	    }
 });
if(document.getElementById('divId').children.length==3){
	document.getElementById('preview').children[1].setAttribute("type","");
}
$("input[type=file]").live("change" ,function(){
		ajaxfileuploadUtils(this,"product",photoFile,i);
		if(picnum>=3){
			$('#picturePathInput').css("display","none");
			//alert("最多上传三张照片！");
		}
	
});
});

//提交
function sub(){	
	var str = $("#fromProduct").serialize();
	/*i = 0;
	picnum = 0;*/
	PicturePath1 = "";
	PicturePath2 = "";
	PicturePath3 = "";
	//console.log(str);return;
	//var mobile = "";
	console.log($("#fromProduct").serialize().split("&").length);
	for (var int = 0; int < str.split("&").length; int++) {
		if (str.indexOf("mobile"+int)>0 || str.indexOf("countyId"+int)>0) {
			str = str.replace("mobile"+int,'mobile');
			str = str.replace("countyId"+int,'countyId');
		}
		
	}
	str = str.replace('picturePath1Input1','PicturePath1');
	str = str.replace('picturePath1Input2','PicturePath2');
	str = str.replace('picturePath1Input3','PicturePath3');
	//console.log(str);
	//return;
		if($("#fromProduct").valid()){
			
			$.ajax({
				url:server_url+'rest/saleManager/insertSkuProduct.do?ran='+Math.random()+ '&token=' + token,
				type:'post',
				data:str,
				async:false,
				success:function(data){
					easyDialog.open({container:{header:'温馨提示',content:data.retMsg},autoClose : 2000});
					back();
				}
			});
		}	
}
/*function checkIsExist(){
	$.ajax({
		url:server_url,
 type:"get",
		async:false,
		data:
	})
}*/
function back(){
	var url="skuProductList.do?ran="+Math.random();
	tl_config.loadToWorkArea(url);
}

function submitCommit(){
	$("#fromProduct").submit();
}
//初始化商品类型下拉列表
function InitParentCate(){
	$.ajax({
		url:server_url+'/rest/productCate/selectParentCate.do?ran='+Math.random()+"&token="+token,
		type:'get',
		success:function(data){
			if(data.retCode=="0000"){
				for(var i=0;i<data.data.length;i++){
					$("#parentCate1").append("<option value='"+data.data[i].cateId+"'>"+data.data[i].cateName+"</option>");
				}
			}
			else{
				easyDialog.open({
					  container : {
						  header : '提示',
					      content : data.retMsg
					  },
					  autoClose : 2000
					});				
			} 			
		}
	});	
}

//切换子级分类
function changeChildKv(parentId,remove){
	$("#parentCate2").html('<option value="">请选择</option>');
	$("#productName").html('<option value="">请选择</option>');
	$("#catchId").html('<option value="">请选择</option>');
	$("#specId").html('<option value="">请选择</option>');
	$("#weightId").html('<option value="">请选择</option>');
	$.ajax({
		url:server_url+'/rest/productCate/selectChildCateKv.do?ran='+Math.random()+"&token="+token,
		type:'post',
		data:{cateId:parentId},
		success:function(data){
			if(data.retCode=="0000"){
				for(var i=0;i<data.data.length;i++){
					$("#parentCate2").append("<option value='"+data.data[i].cateId+"'>"+data.data[i].cateName+"</option>");
				}
             }
			else{
				easyDialog.open({
					  container : {
						  header : '提示',
					    content : data.retMsg
					  },
					  autoClose : 2000
					});			
			}
		}
	});
}
//切换二级分类选择商品
function InitProduct(cateId){
	$("#productName").html('<option value="">请选择</option>');
	$.ajax({
		url:server_url+'rest/product/getProductNameByCateId.do?ran='+Math.random()+"&token="+token,
		type:'post',
		data:{cateId:cateId},
		success:function(data){
			if(data.retCode=="0000"){
				for(var i=0;i<data.data.nameList.length;i++){
					var html = "<option value='"+data.data.nameList[i].productId+"'>"+data.data.nameList[i].productName+"</option>";
					$(html).appendTo("#productName");
				}	
             }
			else{
				easyDialog.open({
					  container : {
						  header : '提示',
					    content : data.retMsg
					  },
					  autoClose : 2000
					});			
			}
		}
	});
}

//切换二级分类选择属性
function changeParentBrandIdKv(cateId){
	$("#catchId").html('<option value="">请选择</option>');
	$("#specId").html('<option value="">请选择</option>');
	$("#weightId").html('<option value="">请选择</option>');
	$.ajax({
		url:server_url+'/rest/product/selectByCateId.do?ran='+Math.random()+"&token="+token,
		type:'post',
		data:{cateId:cateId},
		success:function(data){
			if(data.retCode=="0000"){
				InitSpec(data.data);
             }
			else{
				easyDialog.open({
					  container : {
						  header : '提示',
					    content : data.retMsg
					  },
					  autoClose : 2000
					});			
			}
		}
	});
};
//输出Dom
function InitSpec(data){
	for(var i =0;i<data.length;i++){
		if(data[i].specName=="规格"){
			var html="<option value="+data[i].specValueId+">"+data[i].specValueName+"</option>";
			$(html).appendTo("#specId");
		}
		if(data[i].specName=="捕捞方式"){
			var html="<option value="+data[i].specValueId+">"+data[i].specValueName+"</option>";
			$(html).appendTo("#catchId");
		}
		if(data[i].specName=="件重"){
			var html="<option value="+data[i].specValueId+">"+data[i].specValueName+"</option>";
			$(html).appendTo("#weightId");
		}
	}
};
//添加区域列表行
function addAreaLi(key,value){
	if(key == undefined || key == null){
		key = "";
	}
	if(value == undefined || value == null){
		value = "";
	}
	// 表示现在到第几行
	var index = $("#area li").size();
			$("#area").append(""+
					'<li id="keyValue'+index+'Tr" class="clearfix" >' +
								'<span>&nbsp;&nbsp;&nbsp;&nbsp;</span>'+
     				    		' <select style="width:100px;" name="provinceName" id="provinceId'+index+'" onchange="selectProvince(this);">'+
                                
		                        '</select>'+
     				    		'<select style="width:100px;" name="cityName" id="cityId'+index+'" onchange="selectCity(this);">'+
     				    		
				    	  	 	'</select>'+
		    	  	 			' <select style="width:100px;" name="countyId'+index+'" id="countyId'+index+'">'+
		    	  	 			
     				    		'</select>'+
     				    		//'<input name="key" id="key'+index+'" type="hidden" value="'+key+'" maxlength="100"/>' +
     				    		'<td><a href="javascript:delRow('+index+');" class="z_delpost">删除</a></td>'+
     				    	"</li>"
     				   
     				    
		);
			
			queryProvince(document.getElementById("provinceId"+index));
	
};
//添加个人列表行
function addPersonLi(key,value){
	if(key == undefined || key == null){
		key = "";
	}
	if(value == undefined || value == null){
		value = "";
	}
	// 表示现在到第几行
	var index = $("#person li").size();
	console.log(index);
			$("#person").append(""+
					'<li id="keyValue'+index+'Tr" class="clearfix">' +
								'<span>&nbsp;&nbsp;&nbsp;&nbsp;</span>'+
       				    		'<input name="mobile'+index+'" id="mobilw'+index+'" type="text" value="'+key+'" maxlength="100"/>' +
     				    		'<td><a href="javascript:delRow('+index+');" class="z_delpost">删除</a></td>'+
     				    	"</li>"
     				    
		);
	num = index;
};
//删除列表行
function delRow(index) {
	$("#keyValue"+index+"Tr").remove();
}
function queryProvince(pro){
	var html="<option value='' selected='selected'>"+"省/直辖市"+"</option>";
	$.ajax({
		type:"get",
		url:server_url+"rest/areaManager/getProvince.do?token="+$("body").data("token"),
		async:false,
		success:function(data){
			for(var i=0;i<data.data.length;++i){
				html +="<option value="+data.data[i].areaId+">"+data.data[i].areaName+"</option>";
				
			}
			$(pro).html(html);
		}
	});
}
function selectProvince(pro){
	queryCity($(pro).val(),pro);
}
function selectCity(city){
	queryCounty($(city).val(),city);
}
function queryCity(id,sel){
	$.ajax({
		type:"get",
		url:server_url+"rest/areaManager/getByParent.do?token="+$("body").data("token"),
		data:{
			parentId:id
		},
		async:false,
		success:function(data){
			var html="<option value='' selected='selected'>"+"市/区"+"</option>";
			if(data.data!=null){
				for(var i=0;i<data.data.length;++i){
					html +="<option value="+data.data[i].areaId+">"+data.data[i].areaName+"</option>";
				};
				$(sel).next().html(html);
			}else{
				$(sel).next().html(html);
			}
		}
	});
}

function queryCounty(id,sel){
	$.ajax({
		type:"get",
		url:server_url+"rest/areaManager/getByParent.do?token="+$("body").data("token"),
		data:{
			parentId:id
		},
		async:false,
		success:function(data){
			var html="<option value='' selected='selected'>"+"县"+"</option>";
			if(data.data!=null){
				
				for(var i=0;i<data.data.length;++i){
					html +="<option value="+data.data[i].areaId+">"+data.data[i].areaName+"</option>";
				}
				$(sel).next().html(html);
			}else{
				$(sel).next().html(html);
			}
		}
	});
}
function photoFile(data,input,ii){
	if(data.data == null){return;}
	i++;
	picnum++;
	if(document.getElementById('divId').children.length<3){
		if(ii+=1){
			$("#picturePathInput").parent("span").next().append('<em id="emId'+ii+'" class="spanC" onclick="del('+ii+');"><input type="hidden" name="picturePath1Input'+ii+'" id="picturePathInput'+ii+'"><img id="picturePath'+i+'" src="" class="numImg1"><img class="clo" id="photo'+ii+'"/></em>');
			var id = jQuery(input).attr("id").substring(11);
			console.log(ii);
			if (data.retCode = "0000") {
				var path= data.data;
				if(jQuery("#picturePath"+ii+"").attr("src")=="" ){
						jQuery("#picturePathInput"+ii+"").val(path);
						jQuery("#picturePath"+ii+"").attr("src",path);
						document.getElementById("picturePath"+ii+"").getAttribute("src");
						jQuery("#photo"+ii+"").attr("src","images/close.png");
				}
			}else{
				easyDialog.open({
					container:{
						header:"温馨提示",
						content:'上传失败'
					},
					noFn : true							
				});
			}
		}
	}else{
		alert("最多增加三张照片！");
	}	
};
//删除
function del(a){
	$("#photo"+a+"").attr("src","");
	$('#emId'+a+'').remove();
	if((undefined == $("#emId1").attr("class") && undefined == $("#emId2").attr("class") && undefined == $("#emId3").attr("class")) || (undefined == $("#emId1").attr("class") && undefined == $("#emId2").attr("class") && undefined != $("#emId3").attr("class"))){
		i = 0;
	}else if(undefined != $("#emId1").attr("class") && undefined == $("#emId2").attr("class") && undefined == $("#emId3").attr("class")){
		i = 1;
	}else if(undefined == $("#emId1").attr("class") && undefined != $("#emId2").attr("class") && undefined == $("#emId3").attr("class")){
		$("#divId").children().attr("id","emId1");
		$("#divId").children().attr("onclick","del(1)");
		$("#divId").children().find("input").attr("name","picturePath1Input1");
		$("#divId").children().find("input").attr("id","picturePath1Input1");
		$("#divId").children().find("img").eq(0).attr("id","picturePath1");
		$("#divId").children().find("img").eq(1).attr("id","photo1");
		i = 1;
	}else {
		i = a -1;
	}
		
	picnum--;
	if(picnum<3){
		$('#picturePathInput').css("display","block");
	}
	
};